package com.pn.taikao.service.impl;

import com.pn.taikao.common.ResultCode;
import com.pn.taikao.entity.College;
import com.pn.taikao.exception.BusinessException;
import com.pn.taikao.mapper.CollegeMapper;
import com.pn.taikao.service.CollegeService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CollegeServiceImpl implements CollegeService {

    private final CollegeMapper collegeMapper;

    public CollegeServiceImpl(CollegeMapper collegeMapper) {
        this.collegeMapper = collegeMapper;
    }

    @Override
    public Long createCollege(College college) {
        // 检查学院名称是否已存在
        if (StringUtils.hasText(college.getName())) {
            College exist = collegeMapper.selectByName(college.getName());
            if (exist != null) {
                throw new BusinessException(ResultCode.PARAM_ERROR, "学院名称已存在");
            }
        }
        
        if (college.getCreateTime() == null) {
            college.setCreateTime(LocalDateTime.now());
        }
        if (college.getUpdateTime() == null) {
            college.setUpdateTime(LocalDateTime.now());
        }
        collegeMapper.insert(college);
        return college.getId();
    }

    @Override
    public void updateCollege(College college) {
        // 检查学院名称是否已存在（排除自己）
        if (StringUtils.hasText(college.getName())) {
            College exist = collegeMapper.selectByName(college.getName());
            if (exist != null && !exist.getId().equals(college.getId())) {
                throw new BusinessException(ResultCode.PARAM_ERROR, "学院名称已存在");
            }
        }
        college.setUpdateTime(LocalDateTime.now());
        collegeMapper.update(college);
    }

    @Override
    public void deleteCollege(Long id) {
        collegeMapper.deleteById(id);
    }

    @Override
    public College getById(Long id) {
        return collegeMapper.selectById(id);
    }

    @Override
    public List<College> getAll() {
        return collegeMapper.selectAll();
    }

    @Override
    public List<College> list(String name, int page, int size) {
        int offset = Math.max(page, 1);
        offset = (offset - 1) * Math.max(size, 1);
        return collegeMapper.selectPage(name, offset, size);
    }

    @Override
    public long count(String name) {
        return collegeMapper.count(name);
    }
}













